#include "http.hpp"

#define WWWROOT "./wwwroot/"

std::string RequestStr(const HttpRequest& req)
{
    std::stringstream ss;
    //请求方法 资源路径 协议版本
    ss << req._method <<" " << req._path <<" " << req._version <<"\r\n";
    //查询字符串
    for(auto& it : req._parame)
    {
        ss << it.first <<": " <<it.second << "\r\n";
    }
    //请求头部
    for(auto& it : req._headers)
    {
        ss << it.first <<": " <<it.second << "\r\n";
    }
    ss << "\r\n";
    //请求正文
    ss << req._body;
    return ss.str();
}

void GetFile(const HttpRequest& req,HttpResponse* resp)
{
    resp->SetContent(RequestStr(req),"text.plain");
    //sleep(15); //这里模拟服务器处理时间很长，可能会导致的其他连接超时销毁
}
void Login(const HttpRequest& req,HttpResponse* resp)
{
    resp->SetContent(RequestStr(req),"text.plain");
}
void PutFile(const HttpRequest& req,HttpResponse* resp)
{
    std::string req_path = WWWROOT + req._path;
    Util::WriteFile(req_path,req._body);
}
void DeleteFile(const HttpRequest& req,HttpResponse* resp)
{
    resp->SetContent(RequestStr(req),"text.plain");
}

int main()
{
    HttpServer server(8080);
    server.SetBaseDir(WWWROOT);
    server.SetThreadCount(3);
    server.Get("/hello",GetFile);
    server.Post("/login",Login);
    server.Put("/submit.txt",PutFile);
    server.Delete("/submit.txt",DeleteFile);
    server.Listen();
    return 0;
}